﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Windows;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;
using System.ComponentModel.DataAnnotations;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Media3D;

namespace SQLite_Email_Sending.ViewModels
{
    public partial class MainWindowViewModel : ObservableValidator
    {
        private string connectionString = "Data Source=recipients.db;Version=3;";
        private ObservableCollection<Recipient> receivers = new ObservableCollection<Recipient>();

        public ObservableCollection<Recipient> Receivers
        {
            get => receivers;
            set => SetProperty(ref receivers, value);
        }
        public MainWindowViewModel()
        {
            CreateRecipientTable();
            LoadRecipients();
        }

        [ObservableProperty]
        private string sender;

        [ObservableProperty]
        private string aUTHORIZECODE;//wcxrouinakxkdffb

        [ObservableProperty]
        [Required(ErrorMessage ="用户名不能为空")]
        [MaxLength(20,ErrorMessage ="姓名长度不能超过20位")]
        private string name;

        [ObservableProperty]
        [Required(ErrorMessage ="邮箱地址不能为空")]
        [EmailAddress(ErrorMessage ="邮箱地址格式不正确")]
        [MaxLength(50,ErrorMessage ="邮箱地址长度不能超过50位")]
        private string address;

        [ObservableProperty]
        private string title;
        [ObservableProperty]
        private string body;
        //[ObservableProperty]
        private Recipient selectedItem;
        public Recipient SelectedItem
        {
            get => selectedItem;
            set
            {
                if (SetProperty(ref selectedItem, value) && value !=null) 
                {
                    OnRecipientSelected(value);
                } 
            } 
        }
        private void OnRecipientSelected(Recipient value)
        {
            Name = value.Name;
            Address = value.Email;
        }

        [ObservableProperty]
        string? userNameErrorMessage;
        [ObservableProperty]
        string? emailErrorMessage;
        [ObservableProperty]
        string? senderAddressErrorMessage;
        [ObservableProperty]
        string? aUTHORIZECODEErrorMessage;
        //表结构
        #region
        public class Recipient
        {
            public int Id { get; set; }
            public string? Name { get; set; }
            public string? Email { get; set; }

            public override string ToString()
            {
                return $"{Name} <{Email}>";
            }
        }
        #endregion
        //连接数据库，创建数据表ReRecipients
        #region
        private void CreateRecipientTable()
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string createTableQuery = @"
                    CREATE TABLE IF NOT EXISTS Recipients (
                        Id INTEGER PRIMARY KEY AUTOINCREMENT,
                        Name TEXT NOT NULL,
                        Email TEXT NOT NULL
                    );";
                using (SQLiteCommand command = new SQLiteCommand(createTableQuery, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
        #endregion
        //读取数据表显示到Listview上
        #region
        private void LoadRecipients()
        {
            Receivers.Clear();
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string selectQuery = "SELECT Id, Name, Email FROM Recipients;";
                using (SQLiteCommand command = new SQLiteCommand(selectQuery, connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            int id = reader.GetInt32(0);
                            string name = reader.GetString(1);
                            string email = reader.GetString(2);
                            Receivers.Add(new Recipient { Id = id, Name = name, Email = email });
                        }
                    }
                }
            }
        }
        #endregion
        //添加收件人
        #region
        [RelayCommand]
        private void AddReceiver()
        {
           
            ValidateAllProperties();//使用Validator校验
            if (HasErrors)
            {
                UserNameErrorMessage = string.Join(Environment.NewLine, GetErrors(nameof(Name)));//获取特定字段错误信息
                EmailErrorMessage = string.Join(Environment.NewLine, GetErrors(nameof(Address)));
                return;//如果有错误return掉
            }
            UserNameErrorMessage = "";
            EmailErrorMessage = "";
            string name = Name;
            string email = Address;
            if (IsRecipientExist(name, email))
            {
                MessageBox.Show("邮箱已存在");
                return;
            }
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email))
            {
                MessageBox.Show("请输入姓名和邮箱地址");
                return;
            }

            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string insertQuery = "INSERT INTO Recipients (Name, Email) VALUES (@Name, @Email);";
                using (SQLiteCommand command = new SQLiteCommand(insertQuery, connection))
                {
                    command.Parameters.AddWithValue("@Name", name);
                    command.Parameters.AddWithValue("@Email", email);
                    command.ExecuteNonQuery();
                }
            }

            LoadRecipients();
            Name = "";
            Address = "";
        }
        [RelayCommand]
        private void DeleteReceiver()
        {
            ValidateAllProperties();
            UserNameErrorMessage = "";
            EmailErrorMessage = "";
            if (SelectedItem != null)
            {
                Recipient selectedRecipient = SelectedItem;
                using (SQLiteConnection connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();
                    string deleteQuery = "DELETE FROM Recipients WHERE Id = @Id;";
                    using (SQLiteCommand command = new SQLiteCommand(deleteQuery, connection))
                    {
                        command.Parameters.AddWithValue("@Id", selectedRecipient.Id);
                        command.ExecuteNonQuery();
                    }
                }
                LoadRecipients();
                Name = "";
                Address = "";
            }
            else
            {
                MessageBox.Show("请选择要删除的收件人");
            }
        }
        #endregion
        //删除收件人
        #region
        [RelayCommand]
        private void UpdateReceiver()
        {
            ValidateAllProperties();
            if (HasErrors)
            {
                UserNameErrorMessage = string.Join(Environment.NewLine, GetErrors(nameof(Name)));//获取特定字段错误信息
                EmailErrorMessage = string.Join(Environment.NewLine, GetErrors(nameof(Address)));
                return;//如果有错误return掉
            }
            UserNameErrorMessage = "";
            EmailErrorMessage = "";
            if (Receivers != null)
            {
                Recipient selectedRecipient = SelectedItem;
                string name = Name;
                string email = Address;

                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email))
                {
                    MessageBox.Show("请输入姓名和邮箱地址");
                    return;
                }

                using (SQLiteConnection connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();
                    string updateQuery = "UPDATE Recipients SET Name = @Name, Email = @Email WHERE Id = @Id;";
                    using (SQLiteCommand command = new SQLiteCommand(updateQuery, connection))
                    {
                        command.Parameters.AddWithValue("@Name", name);
                        command.Parameters.AddWithValue("@Email", email);
                        command.Parameters.AddWithValue("@Id", selectedRecipient.Id);
                        command.ExecuteNonQuery();
                    }
                }
                LoadRecipients();
                Name="";
                Address = "";
            }
            else
            {
                MessageBox.Show("请选择要更新的收件人");
            }
        }
        #endregion
        //发送邮件
        #region
        [RelayCommand]
        private void SendEmail()
        {
            if (string.IsNullOrEmpty(AUTHORIZECODE))
            {
                MessageBox.Show("授权码为空");
                return;
            }
            if (Receivers.Count == 0)
            {
                MessageBox.Show("缺少邮件地址信息");
                return;
            }
            if (string.IsNullOrEmpty(Title) || string.IsNullOrEmpty(Body))
            {
                MessageBox.Show("缺少邮件内容信息");
                return;
            }
            try
            {
                sendEmail(Title, Body);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送邮件失败：{ex.Message}");
            }
        }
        private async void sendEmail(string subject, string body)
        {
            string smtpServer = "smtp.qq.com";
            int smtpPort = 587;
            string fromEmail = Sender;  // 发件人QQ邮箱
            string fromPassword = AUTHORIZECODE;
            try
            {
                var smtpClient = new SmtpClient(smtpServer)
                {
                    Port = smtpPort,
                    Credentials = new NetworkCredential(fromEmail, fromPassword),
                    EnableSsl = true
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(fromEmail),
                    Subject = subject,
                    Body = body
                };

                //mailMessage.To.Add(Reciever.Text);  // 收件人邮箱
                //string[] recipientAddresses = Receiver.Text.Split(';');
                List<string> names = new List<string>();
                await Task.Run(() =>
                {
                    foreach (Recipient recipient in Receivers)
                    {
                        if (string.IsNullOrEmpty(recipient.Email))
                        {
                            MessageBox.Show($"收件人邮箱地址 {recipient.Email} 格式不正确");
                            return;
                        }
                        mailMessage.To.Add(recipient.Email);
                        names.Add(recipient.Name);
                    }
                    smtpClient.Send(mailMessage);

                    StringBuilder sb = new StringBuilder();
                    foreach (string name in names)
                    {
                        sb.AppendLine(name);
                    }
                    MessageBox.Show($"邮件发送成功!\n收件人:\n{sb}");
                });
                //MessageBox.Show($"邮件发送成功");
                //Logger.WriteLog($"邮件已发送到{ReceiveEmailAddress},内容为{Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
                return;
            }
        }
        #endregion
        //验证逻辑
        #region
        //邮箱格式验证逻辑
        /*private bool IsValidEmail(string email)
        {
            // 简单的邮箱格式验证正则表达式
            string pattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
            return Regex.IsMatch(email, pattern);
        }*/
        //重复收件人验证逻辑
        private bool IsRecipientExist(string name, string email)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                string selestQuery = "SELECT COUNT(*) FROM Recipients WHERE Name = @Name AND Email = @Email;";
                using (SQLiteCommand command = new SQLiteCommand(selestQuery, connection))
                {
                    command.Parameters.AddWithValue($"@Name", name);
                    command.Parameters.AddWithValue($"@Email", email);
                    int count = Convert.ToInt32(command.ExecuteScalar());
                    return count > 0;
                }
            }
        }
        #endregion
    }
    
}
